// pages/hotel/order.js
import {
    hotel,
    store,
    gourmet,
    platform
} from '../../api/apiData'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        bannerList: [{
            path: '/images/banner.png',
            url: ''
        }],
        obj: '',
        contact_name: '',
        contact_phone: '',
        note: '',
        order_id: '',
        order_no: '',
        dayNum: '',
        minutes: '',
        timeData: {},
        type:0,
        show:false,
        beforeClose(action){
            return new Promise(resolve=>{
                if(action==='confirm'){
                    resolve(false)
                }else{
                    resolve(true)
                }
            })
        },
        reason:''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let id = options.id
        this.setData({
            order_id: id,
            type:options.type
        })
        this.getDetail()
    },
    // 确认收货
    toReceive(){
        let that = this
        wx.showModal({
            title: '提示',
            content: '确定要确认收货吗？',
            showCancel: true, //是否显示取消按钮
            cancelText: "否", //默认是“取消”
            confirmText: "是", //默认是“确定”
            success: function (res) {
              if (res.cancel) {
                //点击取消,默认隐藏弹框
      
              } else {
                //点击确定
                store.order.receive({
                    order_id: that.data.order_id
                }, res => {
                    if (res.code == 1) {
                        wx.showToast({
                            title: res.msg,
                        })
                        setTimeout(() => {
                            that.getDetail()
                        }, 500)
                    } else {
                        wx.showToast({
                            title: res.msg,
                            icon: 'error'
                        })
                    }
                })
              }
            },
            fail: function (res) {}, //接口调用失败的回调函数
            complete: function (res) {}, //接口调用结束的回调函数（调用成功、失败都会执行）
          })
    },
    inputChange(e) {
        let fieldName = e.target.dataset.name
        this.setData({
            [`${fieldName}`]: e.detail.value
        })
    },
    onChange(e) {
        this.setData({
            timeData: e.detail,
        });
    },
    //   取消订单
    toCancel() {
        let that = this
        wx.showModal({
            title: '提示',
            content: '确定要取消订单吗？',
            showCancel: true, //是否显示取消按钮
            cancelText: "否", //默认是“取消”
            confirmText: "是", //默认是“确定”
            success: function (res) {
              if (res.cancel) {
                //点击取消,默认隐藏弹框
      
              } else {
                //点击确定
                hotel.order.cancel({
                    order_id: that.data.order_id
                }, res => {
                    if (res.code == 1) {
                        wx.showToast({
                            title: res.msg,
                        })
                        setTimeout(() => {
                            that.getDetail()
        
                        }, 500)
                    } else {
                        wx.showToast({
                            title: res.msg,
                            icon: 'error'
                        })
                    }
                })
              }
            },
            fail: function (res) {}, //接口调用失败的回调函数
            complete: function (res) {}, //接口调用结束的回调函数（调用成功、失败都会执行）
          })
      
    },
    toCancel2() {
        let that = this
        wx.showModal({
            title: '提示',
            content: '确定要取消订单吗？',
            showCancel: true, //是否显示取消按钮
            cancelText: "否", //默认是“取消”
            confirmText: "是", //默认是“确定”
            success: function (res) {
              if (res.cancel) {
                //点击取消,默认隐藏弹框
      
              } else {
                //点击确定
                store.order.cancel({
                    order_id: that.data.order_id
                }, res => {
                    if (res.code == 1) {
                        wx.showToast({
                            title: res.msg,
                        })
                        setTimeout(() => {
                            that.getDetail()
        
                        }, 500)
                    } else {
                        wx.showToast({
                            title: res.msg,
                            icon: 'error'
                        })
                    }
                })
              }
            },
            fail: function (res) {}, //接口调用失败的回调函数
            complete: function (res) {}, //接口调用结束的回调函数（调用成功、失败都会执行）
          })
      
    },
    toCancel3() {
        let that = this
        wx.showModal({
            title: '提示',
            content: '确定要取消订单吗？',
            showCancel: true, //是否显示取消按钮
            cancelText: "否", //默认是“取消”
            confirmText: "是", //默认是“确定”
            success: function (res) {
              if (res.cancel) {
                //点击取消,默认隐藏弹框
      
              } else {
                //点击确定
                gourmet.order.cancel({
                    order_id: that.data.order_id
                }, res => {
                    if (res.code == 1) {
                        wx.showToast({
                            title: res.msg,
                        })
                        setTimeout(() => {
                            that.getDetail()
        
                        }, 500)
                    } else {
                        wx.showToast({
                            title: res.msg,
                            icon: 'error'
                        })
                    }
                })
              }
            },
            fail: function (res) {}, //接口调用失败的回调函数
            complete: function (res) {}, //接口调用结束的回调函数（调用成功、失败都会执行）
          })
      
    },
    toCancel4() {
        let that = this
        wx.showModal({
            title: '提示',
            content: '确定要取消订单吗？',
            showCancel: true, //是否显示取消按钮
            cancelText: "否", //默认是“取消”
            confirmText: "是", //默认是“确定”
            success: function (res) {
              if (res.cancel) {
                //点击取消,默认隐藏弹框
      
              } else {
                //点击确定
                platform.guide.orderCancel({
                    order_id: that.data.order_id
                }, res => {
                    if (res.code == 1) {
                        wx.showToast({
                            title: res.msg,
                        })
                        setTimeout(() => {
                            that.getDetail()
        
                        }, 500)
                    } else {
                        wx.showToast({
                            title: res.msg,
                            icon: 'error'
                        })
                    }
                })
              }
            },
            fail: function (res) {}, //接口调用失败的回调函数
            complete: function (res) {}, //接口调用结束的回调函数（调用成功、失败都会执行）
          })
      
    },
    toShow(){
        this.setData({
            show:true
        })
    },
    // 民宿退款
    toRefund(){
        let that = this
        if(that.data.reason==''){
            wx.showToast({
              title: '请输入退款原因',
              icon:'error'
            })
            return false
        }
        wx.showModal({
            title: '提示',
            content: '确定要申请退款吗？',
            showCancel: true, //是否显示取消按钮
            cancelText: "否", //默认是“取消”
            confirmText: "是", //默认是“确定”
            success: function (res) {
              if (res.cancel) {
                //点击取消,默认隐藏弹框
      
              } else {
                //点击确定
                if(that.data.type==0){
                    hotel.order.refund({
                        order_id: that.data.order_id,
                        reason:that.data.reason
                    }, res => {
                        if (res.code == 1) {
                            wx.showToast({
                                title: res.msg,
                            })
                            setTimeout(() => {
                                that.getDetail()
                                that.setData({
                                    show:false
                                })
                            }, 500)
                        } else {
                            that.setData({
                                show:false
                            })
                            wx.showToast({
                                title: res.msg,
                                icon: 'error'
                            })
                        }
                    })
                }
                if(that.data.type==1){
                    store.order.refund({
                        order_id: that.data.order_id,
                        reason:that.data.reason
                    }, res => {
                        if (res.code == 1) {
                            wx.showToast({
                                title: res.msg,
                            })
                            setTimeout(() => {
                                that.getDetail()
                                that.setData({
                                    show:false
                                })
                            }, 500)
                        } else {
                            that.setData({
                                show:false
                            })
                            wx.showToast({
                                title: res.msg,
                                icon: 'error'
                            })
                        }
                    })
                }
                if(that.data.type==3){
                    platform.guide.orderRefund({
                        order_id: that.data.order_id,
                        reason:that.data.reason
                    }, res => {
                        if (res.code == 1) {
                            wx.showToast({
                                title: res.msg,
                            })
                            setTimeout(() => {
                                that.getDetail()
                                that.setData({
                                    show:false
                                })
                            }, 500)
                        } else {
                            that.setData({
                                show:false
                            })
                            wx.showToast({
                                title: res.msg,
                                icon: 'error'
                            })
                        }
                    })
                }
              }
            },
            fail: function (res) {}, //接口调用失败的回调函数
            complete: function (res) {}, //接口调用结束的回调函数（调用成功、失败都会执行）
          })
    },
    beforeClose(event){
     console.log(action)
    },
    // 预定
    toOrder() {
        let obj = this.data.obj
        obj.contact_name = this.data.contact_name
        obj.contact_phone = this.data.contact_phone
        obj.note = this.data.note
        console.log(obj)
        if (obj.contact_name == '') {
            wx.showToast({
                title: '请输入住客姓名',
                icon: 'error'
            })
        }
        if (obj.contact_phone == '') {
            wx.showToast({
                title: '请输入联系电话',
                icon: 'error'
            })
        }
        let that = this
        hotel.order.submit(obj, res => {
            if (res.code == 1) {
                wx.showToast({
                    title: res.msg,
                })
                that.setData({
                    order_id: res.data.id,
                    order_no: res.data.order_no,
                })
                that.toPay()
            } else {
                wx.showToast({
                    title: res.msg,
                    icon: 'error'
                })
            }
        })

    },
    getDetail() {
        if(this.data.type==0){
            hotel.order.detail({
                order_id: this.data.order_id,
            }, res => {
                if (res.code == 1) {
                    let dayNum = this.calculateDaysDifference(res.data.checkin_date, res.data.checkout_date)
                    this.setData({
                        info: res.data,
                        order_no: res.data.order_no,
                        dayNum,
                    })
                    if (res.data.status == 1) {
                        const minutes = this.calculateMinutesBetweenDates(res.data.expire_time);
                        console.log(minutes); // 输出：30
                        this.setData({
                            minutes: minutes
                        })
                    }
    
                } else {
                    wx.showToast({
                        title: res.msg,
                        icon: 'error'
                    })
                }
            })
        }
        if(this.data.type==1){
            store.order.detail({
                order_id: this.data.order_id,
            }, res => {
                if (res.code == 1) {
                    let dayNum = this.calculateDaysDifference(res.data.checkin_date, res.data.checkout_date)
                    this.setData({
                        info: res.data,
                        order_no: res.data.order_no,
                        dayNum,
                    })
                    if (res.data.status == 1) {
                        const minutes = this.calculateMinutesBetweenDates(res.data.expire_time);
                        console.log(minutes); // 输出：30
                        this.setData({
                            minutes: minutes
                        })
                    }
    
                } else {
                    wx.showToast({
                        title: res.msg,
                        icon: 'error'
                    })
                }
            })
        }
        if(this.data.type==2){
            gourmet.order.detail({
                order_id: this.data.order_id,
            }, res => {
                if (res.code == 1) {
                    let dayNum = this.calculateDaysDifference(res.data.checkin_date, res.data.checkout_date)
                    this.setData({
                        info: res.data,
                        order_no: res.data.order_no,
                        dayNum,
                    })
                    if (res.data.status == 1) {
                        const minutes = this.calculateMinutesBetweenDates(res.data.expire_time);
                        console.log(minutes); // 输出：30
                        this.setData({
                            minutes: minutes
                        })
                    }
    
                } else {
                    wx.showToast({
                        title: res.msg,
                        icon: 'error'
                    })
                }
            })
        }
        if(this.data.type==3){
            platform.guide.orderDetail({
                order_id: this.data.order_id,
            }, res => {
                if (res.code == 1) {
                    this.setData({
                        info: res.data,
                        order_no: res.data.order_no,
                    })
                    if (res.data.status == 1) {
                        const minutes = this.calculateMinutesBetweenDates(res.data.expire_time);
                        console.log(minutes); // 输出：30
                        this.setData({
                            minutes: minutes
                        })
                    }
    
                } else {
                    wx.showToast({
                        title: res.msg,
                        icon: 'error'
                    })
                }
            })
        }
    },
    // 支付
    toPay() {
        let that = this
        let order_no = that.data.order_no
        wx.login({
            success(res) {
                var code = res.code
                wx.showLoading({
                    title: "请稍后...",
                    mask: true
                })
                hotel.order.pay({
                    order_no,
                    code
                }, res => {
                    let ret_code = res.code
                    let ret_msg = res.msg
                    if (ret_code != 1) {
                        //   Toast(ret_msg)
                        wx.showToast({
                            title: ret_msg,
                            icon: 'error'
                        })
                        return
                    }
                    let {
                        nonceStr,
                        paySign,
                        signType,
                        timeStamp
                    } = res.data
                    wx.requestPayment({
                        nonceStr,
                        package: res.data.package,
                        paySign,
                        timeStamp,
                        signType,
                        success(res) {
                            wx.showToast({
                                title: '支付成功',
                                icon: 'success',
                                duration: 1500
                            });
                            setTimeout(() => {
                                that.getDetail()
                            }, 500)
                        },
                        fail(res) {
                            wx.showToast({
                                title: '支付失败',
                                duration: 1500,
                                icon: 'error'
                            });
                            setTimeout(() => {
                                that.getDetail()
                            }, 500)

                        }
                    })
                })
            }
        })
    },
    toPay2() {
        let that = this
        let order_no = that.data.order_no
        wx.login({
            success(res) {
                var code = res.code
                wx.showLoading({
                    title: "请稍后...",
                    mask: true
                })
                store.order.pay({
                    order_no,
                    code
                }, res => {
                    let ret_code = res.code
                    let ret_msg = res.msg
                    if (ret_code != 1) {
                        //   Toast(ret_msg)
                        wx.showToast({
                            title: ret_msg,
                            icon: 'error'
                        })
                        return
                    }
                    let {
                        nonceStr,
                        paySign,
                        signType,
                        timeStamp
                    } = res.data
                    wx.requestPayment({
                        nonceStr,
                        package: res.data.package,
                        paySign,
                        timeStamp,
                        signType,
                        success(res) {
                            wx.showToast({
                                title: '支付成功',
                                icon: 'success',
                                duration: 1500
                            });
                            setTimeout(() => {
                                that.getDetail()
                            }, 500)
                        },
                        fail(res) {
                            wx.showToast({
                                title: '支付失败',
                                duration: 1500,
                                icon: 'error'
                            });
                            setTimeout(() => {
                                that.getDetail()
                            }, 500)

                        }
                    })
                })
            }
        })
    },
    toPay3() {
        let that = this
        let order_no = that.data.order_no
        wx.login({
            success(res) {
                var code = res.code
                wx.showLoading({
                    title: "请稍后...",
                    mask: true
                })
                gourmet.order.pay({
                    order_no,
                    code
                }, res => {
                    let ret_code = res.code
                    let ret_msg = res.msg
                    if (ret_code != 1) {
                        //   Toast(ret_msg)
                        wx.showToast({
                            title: ret_msg,
                            icon: 'error'
                        })
                        return
                    }
                    let {
                        nonceStr,
                        paySign,
                        signType,
                        timeStamp
                    } = res.data
                    wx.requestPayment({
                        nonceStr,
                        package: res.data.package,
                        paySign,
                        timeStamp,
                        signType,
                        success(res) {
                            wx.showToast({
                                title: '支付成功',
                                icon: 'success',
                                duration: 1500
                            });
                            setTimeout(() => {
                                that.getDetail()
                            }, 500)
                        },
                        fail(res) {
                            wx.showToast({
                                title: '支付失败',
                                duration: 1500,
                                icon: 'error'
                            });
                            setTimeout(() => {
                                that.getDetail()
                            }, 500)

                        }
                    })
                })
            }
        })
    },
    toPay4() {
        let that = this
        let order_no = that.data.order_no
        wx.login({
            success(res) {
                var code = res.code
                wx.showLoading({
                    title: "请稍后...",
                    mask: true
                })
                platform.guide.orderPay({
                    order_no,
                    code
                }, res => {
                    let ret_code = res.code
                    let ret_msg = res.msg
                    if (ret_code != 1) {
                        //   Toast(ret_msg)
                        wx.showToast({
                            title: ret_msg,
                            icon: 'error'
                        })
                        return
                    }
                    let {
                        nonceStr,
                        paySign,
                        signType,
                        timeStamp
                    } = res.data
                    wx.requestPayment({
                        nonceStr,
                        package: res.data.package,
                        paySign,
                        timeStamp,
                        signType,
                        success(res) {
                            wx.showToast({
                                title: '支付成功',
                                icon: 'success',
                                duration: 1500
                            });
                            setTimeout(() => {
                                that.getDetail()
                            }, 500)
                        },
                        fail(res) {
                            wx.showToast({
                                title: '支付失败',
                                duration: 1500,
                                icon: 'error'
                            });
                            setTimeout(() => {
                                that.getDetail()
                            }, 500)

                        }
                    })
                })
            }
        })
    },
    calculateMinutesBetweenDates(targetDate) {
        const now = new Date();
        const target = new Date(targetDate);

        // 获取两个日期的毫秒数差
        const differenceInMilliseconds = target.getTime() - now.getTime();

        // 将毫秒差转换为分钟
        // const differenceInMinutes = Math.floor(differenceInMilliseconds / (1000 * 60));

        return differenceInMilliseconds;
    },
    finished() {
        this.getDetail()
    },
    // 计算相差几天
    calculateDaysDifference(date1, date2) {
        // 将日期字符串转换为Date对象
        const d1 = new Date(date1);
        const d2 = new Date(date2);

        // 获取两个日期的时间戳（毫秒数）
        const timeDiff = Math.abs(d2.getTime() - d1.getTime());

        // 将时间戳转换为天数（1000毫秒 * 60秒 * 60分钟 * 24小时）
        const diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));

        return diffDays;
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})